<template>
  <div class="sc-collapse">
    <slot></slot>
  </div>
</template>

<script lang="ts">
export default {
   name: 'ScCollapse',
}
</script>

<script setup lang="ts">
  import {provide, ref, watch} from'vue';
  import type{collapseItemNameTypes,collapseProps,collapseEmits} from './types';
  import {collapseContextKey} from './types';
  const props = withDefaults(defineProps<collapseProps>(),{
    activeNames:() => [],
    accordion:false,
  });
  const activeNames = ref<collapseItemNameTypes[]>(props.activeNames);
  if(props.accordion && props.activeNames.length > 1) {
    console.warn("手风琴插件默认只能展开一个列表项");
    activeNames.value = [activeNames.value[0]];
  }
  // 通过事件维持v-model数据响应
  const $emits = defineEmits<collapseEmits>();
  // 双向监听，保持数据同步
  watch(() => props.activeNames,(newV,oldV) => {
    activeNames.value = newV;
  });
  watch(activeNames,(newV,oldV) => {
    $emits('update:activeNames',newV);
  });

  function itemClick(itemName:collapseItemNameTypes) {
    if(props.accordion) {
      activeNames.value = [activeNames.value[0] === itemName ? "" : itemName];
    } else {
      const index = activeNames.value.indexOf(itemName);
      if(index > -1) {
        activeNames.value.splice(index,1);
      } else {
        activeNames.value.push(itemName);
      }
    }
  }
  provide(collapseContextKey,{
    activeNames:activeNames,
    itemClick
  });
</script>
<style scoped>
@import './style.css';
</style>
